package com.whg.shiro.service.impl;

import com.whg.shiro.dao.RolePermissionMapper;
import com.whg.shiro.dao.UserMapper;
import com.whg.shiro.dao.UserRoleMapper;
import com.whg.shiro.domain.RoleModel;
import com.whg.shiro.domain.UserModel;
import com.whg.shiro.domain.dto.UserQuery;
import com.whg.shiro.domain.vo.RoleVO;
import com.whg.shiro.domain.vo.UserRolesVO;
import com.whg.shiro.service.UserService;
import com.whg.shiro.util.CommonUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author whg
 * @create 2022/9/28 17:13
 * @description：
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public UserRolesVO findUserRolesByUserName(String userName) {
        //业务方法里面加缓存，也可以

        UserModel userModel = findUserByName(userName);
        List<RoleVO> roles = userRoleMapper.findRoleListByUserId(userModel.getId());
        UserRolesVO vo = new UserRolesVO();
        BeanUtils.copyProperties(userModel,vo);
        vo.setRoles(roles);
        return vo;
    }

    @Override
    public UserModel findUserById(int id) {
        UserModel model = userMapper.selectByPrimaryKey(id);
        return model;
    }

    @Override
    public UserModel findUserByName(String userName) {
        UserModel userModel = userMapper.findAllByUsername(userName);
        return userModel;
    }

    @Override
    public void register(UserQuery userQuery) {
        UserModel model = new UserModel();
        model.setUsername(userQuery.getUserName());
        String salt = CommonUtil.getStringNumRandom(4);
        //String salt = null;
        String encryptedPwd = new SimpleHash("md5", userQuery.getPassword(), salt,2).toString();
        model.setPassword(encryptedPwd);
        model.setSalt(salt);
        model.setCreateTime(LocalDateTime.now());
        userMapper.insert(model);
    }
}
